//剩余次数
var leftNumber;
var issendding=0;//数据是否已经传输完毕
//获取页面的实际高度和宽度
var pageSize={
    pageWidth:(window.innerWidth > 0) ? window.innerWidth : screen.width,
    pageHeight: (window.innerHeight > 0) ? window.innerHeight : screen.height
}

var hinders_width=pageSize.pageWidth/3;
var hinders_height=Math.floor(hinders_width*(289/338));
// 障碍物的参数
window.hinders=[
{name:"lp_0",width:hinders_width,height:hinders_height},
{name:"lp_1",width:hinders_width,height:hinders_height},
{name:"lp_2",width:hinders_width,height:hinders_height},
{name:"lp_3",width:hinders_width,height:hinders_height},
{name:"lp_4",width:hinders_width,height:hinders_height},
{name:"lp_5",width:hinders_width,height:hinders_height},
{name:"lp_6",width:hinders_width,height:Math.floor(hinders_width*(379/260))},
];
var realSpeed=2.5;
//设置画布宽高
function setCanvasSize()
{
    var canvas=$("#stage");
    canvas.attr("width",pageSize.pageWidth);
    canvas.attr("height",pageSize.pageHeight);
}
// 龙舟对象
function Ship(ctx){
	gameMonitor.im.loadImage(['/Public/Images/car.png']);
	this.width = Math.floor(pageSize.pageWidth/5);
	this.height = Math.floor(this.width*(479/272));
	this.left = Math.floor(gameMonitor.w*(5/18) - this.width/2);
	this.top = gameMonitor.h - 2*this.height;
    this.isleft=1;
	this.player = gameMonitor.im.createImage('/Public/Images/car.png');

	this.paint = function(){
		ctx.drawImage(this.player, this.left, this.top, this.width, this.height);
	}

	this.setPosition = function(event){
		if(gameMonitor.isMobile()){
			var tarL = event.changedTouches[0].clientX;
			var tarT = event.changedTouches[0].clientY;
		}
		else{
			var tarL = event.offsetX;
			var tarT = event.offsetY;
		}
		this.left = tarL - this.width/2 - 16;
		this.top = tarT - this.height/2;
		if(this.left<0){
			this.left = 0;
		}
		if(this.left>pageSize.pageWidth-this.width){
			this.left = pageSize.pageWidth-this.width;
		}
		 if(this.top<0){
			 this.top = 0;
		 }
		if(this.top>gameMonitor.h - this.height){
			this.top = gameMonitor.h - this.height;
		}
		this.paint();
	}
    this.setLeft=function(){
        if(this.isleft==1)return false;
        this.isleft=1;
        this.left=gameMonitor.w*(5/18) - this.width/2;
        this.paint();
    }
    this.setRight= function () {
        if(this.isleft==0)return false;
        this.isleft=0;
        this.left=gameMonitor.w*(13/18) - this.width/2;
        this.paint();
    }
	this.controll = function(){
		var _this = this;
		var stage = $('#gamepanel');
			move = false;
		stage.on(gameMonitor.eventType.start, function(event){
			_this.setPosition(event);
			move = true;
		}).on(gameMonitor.eventType.end, function(){
			move = false;
		}).on(gameMonitor.eventType.move, function(event){
			event.preventDefault();
			if(move){
				_this.setPosition(event);	
			}
			
		});
	}
	// 碰撞判断
	this.impact = function(zList){
		for(var i=zList.length-1; i>=0; i--){
			var f = zList[i];
			if(f){
				var lw1=f.left-this.left>this.width;
				var lw2=this.left-f.left>f.width;
				var lh1=f.top-this.top>this.height;
				var lh2=this.top-f.top>f.height;
				if(!(lw1||lw2||lh1||lh2)){
					//撞到障碍物了
                    if(f.type!=6){
                        console.log("获得了第"+f.type+"个奖");
                        zList[f.id] = null;
                    }else{
                        alert("碰到炸弹啦！")
                        location.href='gift.html';
                        gameMonitor.stop();

                    }
				}
			}
			
		}
	}
}


// 设置障碍物和背景一起流动
function Hinder(type, left_right, id){
	this.speedUpTime = 300;
	this.id = id;
	this.type = type;
	this.width = hinders[type]["width"];
	this.height = hinders[type]["height"];
    if(left_right==0){
        this.left = pageSize.pageWidth/9;
    }else{
        this.left = pageSize.pageWidth*(5/9);
    }
	this.top = -200;
	//this.speed = 0.04 * Math.pow(1.2, Math.floor(gameMonitor.time/this.speedUpTime));
	this.loop = -100;

	var p = this.type == 0 ? '/Public/Images/'+hinders[type]["name"]+'.png' : '/Public/Images/'+hinders[type]["name"]+'.png';
	this.pic = gameMonitor.im.createImage(p);
}
Hinder.prototype.paint = function(ctx){
	ctx.drawImage(this.pic, this.left, this.top, this.width, this.height);
}
Hinder.prototype.move = function(ctx){
	this.top = ++this.loop * realSpeed;
   // console.log(this.top);
	if(this.top>gameMonitor.h){
	 	gameMonitor.zList[this.id] = null;
	}
	else{
		this.paint(ctx);
	}
}


function ImageMonitor(){
	var imgArray = [];
	return {
		createImage : function(src){
			return typeof imgArray[src] != 'undefined' ? imgArray[src] : (imgArray[src] = new Image(), imgArray[src].src = src, imgArray[src])
		},
		loadImage : function(arr, callback){
			for(var i=0,l=arr.length; i<l; i++){
				var img = arr[i];
				imgArray[img] = new Image();
				imgArray[img].onload = function(){
					if(i==l-1 && typeof callback=='function'){
						callback();
					}
				}
				imgArray[img].src = img
			}
		}
	}
}

var gameMonitor = {
	w : pageSize.pageWidth,
	h : pageSize.pageHeight,
	bgWidth : pageSize.pageWidth,
	// bgHeight : 1126,
	bgHeight:pageSize.pageHeight,
	time : 0,
	timmer : null,
    clockSecond:0,
    clockMinute:0,
	bgloop : 0,
    totalDistance:0,
	genorateSpeed:50,
	im : new ImageMonitor(),
	zList : [],
	bgDistance : 0,//背景位置
	eventType : {
		start : 'touchstart',
		move : 'touchmove',
		end : 'touchend'
	},
	init : function(){
        setCanvasSize();
		var _this = this;
		var canvas = document.getElementById('stage');
		var ctx = canvas.getContext('2d');
		//绘制背景
		var bg = new Image();
		_this.bg = bg;
		bg.onload = function(){
          	ctx.drawImage(bg, 0, 0, _this.bgWidth, _this.bgHeight);          	
		}
		bg.src = '/Public/Images/game_bg.png';
		_this.initListener(ctx);
        $(function(){
            _this.ship = new Ship(ctx);
            _this.ship.paint();
            //_this.ship.controll();
            $("#left_btn").on("click", function () {
                _this.ship.setLeft();
            })
            $("#right_btn").on("click", function () {
                _this.ship.setRight();
            })
            //绑定初始开始游戏按钮
            $("#begin3").show();
        setTimeout(function(){
            $("#begin3").hide();
            $("#begin2").show();
            setTimeout(function(){
                $("#begin2").hide();
                $("#begin1").show();
                setTimeout(function(){
                    $("#begin1").hide();
                    $("#begingo").show();
                    setTimeout(function(){
                        $("#begingo").hide();
                        $("#tip").hide();
                        $("#tip_top").hide();
                        _this.play(ctx)
                    },1000);
                },1000);
            },1000);
        },1000);
        })
	},
	initListener : function(){
		$(document).on(gameMonitor.eventType.move, function(event){
			event.preventDefault();
		});

	},
    play:function(ctx){
        gameMonitor.run(ctx);
    },
    playAgain:function()
    {
        var _this=this;
        var canvas = document.getElementById('stage');
        var ctx = canvas.getContext('2d');
        _this.reset();
        _this.ship = new Ship(ctx);
        _this.ship.controll();
        _this.run(ctx);
    },
	rollBg : function(ctx){
		if(this.bgDistance>=this.bgHeight){
			this.bgloop = 0;
		}
		this.bgDistance = ++this.bgloop * realSpeed;
        this.totalDistance+=realSpeed;
		ctx.drawImage(this.bg, 0, this.bgDistance-this.bgHeight, this.bgWidth, this.bgHeight);
		ctx.drawImage(this.bg, 0, this.bgDistance, this.bgWidth, this.bgHeight);
	},
	run : function(ctx){
		var _this = gameMonitor;
		ctx.clearRect(0, 0, _this.bgWidth, _this.bgHeight);
		_this.rollBg(ctx);
		//绘制龙舟
		_this.ship.paint();
		_this.ship.impact(_this.zList);


		//产生障碍
		_this.genorateHinder();

		//绘制障碍
		for(i=_this.zList.length-1; i>=0; i--){
			var f = _this.zList[i];
			if(f){
				f.paint(ctx);
				f.move(ctx);
			}
			
		}
		_this.timmer = setTimeout(function(){
			gameMonitor.run(ctx);
		}, Math.round(1000/60));
		_this.time++;
        if(_this.time%60)
        {
            _this.clockSecond++;
            if(_this.clockSecond==60)
            {
                _this.clockMinute++;
                _this.clockSecond=0;
            }
            var minute;
            if(_this.clockMinute<10)
            {
                 minute="0"+_this.clockMinute;
            }
            else
            {
                 minute=_this.clockMinute;
            }
            minute=10-minute;
            $("#time").html(minute);
            if(minute==0){
                gameMonitor.stop();
                alert("时间结束啦！");
                location.href='gift.html';
            }
        }
	},
	stop : function(){
		var _this = this
		$('#stage').off(gameMonitor.eventType.start + ' ' +gameMonitor.eventType.move);
		setTimeout(function(){
			clearTimeout(_this.timmer);
		}, 0);
		
	},
	genorateHinder : function(){
		var genRate = this.genorateSpeed; //产生障碍的频率
		var random = Math.random();
		if(random*genRate>genRate-1){
			var left = Math.random()*100;
		var type = Math.floor(left)%7;
        var left_right=Math.floor(left)%2;
			var id = this.zList.length;
			var f = new Hinder(type, left_right, id);
			this.zList.push(f);
		}
	},
	reset : function(){
		this.zList = [];
		this.bgloop = 0;
		this.timmer = null;
		this.time = 0;
        this.clockSecond=0;
        this.clockMinute=0;
        this.totalDistance=0;
        this.genorateSpeed=40;
        realSpeed=2;
        for(var j=blocks.length-1;j>=0;j--)
        {
            blocks[j]["appear"]=0;
            blocks[j]["use"]=0;
        }
	},
	isMobile : function(){
		var sUserAgent= navigator.userAgent.toLowerCase(),
		bIsIpad= sUserAgent.match(/ipad/i) == "ipad",
		bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os",
		bIsMidp= sUserAgent.match(/midp/i) == "midp",
		bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
		bIsUc= sUserAgent.match(/ucweb/i) == "ucweb",
		bIsAndroid= sUserAgent.match(/android/i) == "android",
		bIsCE= sUserAgent.match(/windows ce/i) == "windows ce",
		bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile",
		bIsWebview = sUserAgent.match(/webview/i) == "webview";
		return (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM);
     }
}
if(!gameMonitor.isMobile()){
	gameMonitor.eventType.start = 'mousedown';
	gameMonitor.eventType.move = 'mousemove';
	gameMonitor.eventType.end = 'mouseup';
}
$(function(){
    gameMonitor.init();
})
